package com.stlm2.dems.service;

import com.stlm2.core.common.page.PageView;
import com.stlm2.core.redis.RedisClient;
import com.stlm2.dems.dao.*;
import com.stlm2.dems.entity.*;
import com.stlm2.dems.entity.Collections;
import com.stlm2.util.Memcached;
import com.stlm2.util.codecontent.CodeContent;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang.math.NumberUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;

import com.stlm2.core.base.BaseDao;
import com.stlm2.core.base.impl.BaseServiceImpl;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

@Service("ddmGoodsService")
@Transactional(rollbackForClassName={"java.lang.Exception"}, propagation = Propagation.REQUIRED)
public class DdmGoodsService extends BaseServiceImpl<DdmGoods> {

	@Resource
	private DdmGoodsDao ddmGoodsDao;
	@Resource
	private UserDao userDao;
	@Resource
	private GoodsCategoryDao goodsCategoryDao;
	@Resource
	private GoodsRelateCategoryDao goodsRelateCategoryDao;
	@Resource
	private ValueAddedServicesDao valueAddedServicesDao;
	@Resource
	private GoodsValueAddedServicesDao goodsValueAddedServicesDao;
	@Resource
	private Memcached memcached;
	@Resource
	private PriceRecordDao priceRecordDao;
	@Resource
	private DdmObligationDao ddmObligationDao;
	@Resource
	private CommentsDao commentsDao;
	@Resource
	private GoodsOrderDao goodsOrderDao;
	@Resource
	private InventoryDao inventoryDao;
	@Resource
	private DdmShopDao ddmShopDao;
	@Resource
	private SpecificationDao specificationDao;
	@Resource
	private  GoodSpecificationDao goodSpecificationDao;
	@Resource
	private  CollectionsDao collectionsDao;
	@Resource
	private FootMarkDao footMarkDao;
	@Resource
	private StagesService stagesService;


	@Override
	protected BaseDao <DdmGoods> getDao() {
		return ddmGoodsDao;
	}

	/*
	*zlq
	* 添加商品
	* token:
	* abbreviation:  商品简称
	* name: 商品名称
	* mainImg: 商品主图
	* detailsImg: 商品详情图
	* goodsExplain: 商品说明
	* purchasePrice: 进货价
	* costPrice: 成本价
	* ddPrice:  叮当价
	* memberPrice：会员价
	* isWarranty：是否保修
    * warrantyPeriod： 保修期(单位：月)
    * isImie：是否有唯一码
    * parameter:详细参数
    * safeguard:售后保障
	 */
	public String  add(ModelMap model, String token,String abbreviation, String name ,String mainImg,
					   String detailsImg,String goodsExplain,String purchasePrice,String costPrice,
					   String ddPrice,String memberPrice,boolean isWarranty ,String warrantyPeriod,boolean isImie,String parameter,String safeguard,String keyWord){

		if (StringUtils.isEmpty(token)) {
			return CodeContent.getModelByCode(-1, "", model);
		}
		User loginUser = userDao.getByToken(token);
		if (loginUser == null) {
			return CodeContent.getModelByCode(-1, "", model);
		}
		if (StringUtils.isEmpty(parameter)) {
			return CodeContent.getModelByCode(0, "详细参数不能为空", model);
		}
		parameter=parameter.replace("https://m.9ji.com","");
		if (StringUtils.isEmpty(safeguard)) {
			return CodeContent.getModelByCode(0, "售后保障不能为空", model);
		}
		if (StringUtils.isEmpty(abbreviation)) {
			return CodeContent.getModelByCode(0, "商品简称不能为空", model);
		}
		if (StringUtils.isEmpty(name)) {
			return CodeContent.getModelByCode(0, "商品名称不能为空", model);
		}

		if (StringUtils.isEmpty(mainImg)) {
			return CodeContent.getModelByCode(0, "商品主图不能为空", model);
		}
		if (StringUtils.isEmpty(detailsImg)) {
			return CodeContent.getModelByCode(0, "商品详情图不能为空", model);
		}
		detailsImg=detailsImg.replace("https://m.9ji.com","");
		if (StringUtils.isEmpty(goodsExplain)) {
			return CodeContent.getModelByCode(0, "商品说明不能为空", model);
		}
		if (StringUtils.isEmpty(purchasePrice)) {
			return CodeContent.getModelByCode(0, "进货价不能为空", model);
		}
		if (StringUtils.isEmpty(costPrice)) {
			return CodeContent.getModelByCode(0, "成本价不能为空", model);
		}
		if (StringUtils.isEmpty(memberPrice)) {
			return CodeContent.getModelByCode(0, "会员价不能为空", model);
		}
		if (StringUtils.isEmpty(ddPrice)) {
			return CodeContent.getModelByCode(0, "叮当价不能为空", model);
		}

		if(new BigDecimal(costPrice).compareTo(new BigDecimal(purchasePrice))!=1){
			return CodeContent.getModelByCode(0, "成本价必须大于进货价", model);
		}
		if(new BigDecimal(memberPrice).compareTo(new BigDecimal(costPrice))!=1){
			return CodeContent.getModelByCode(0, "会员价必须大于成本价", model);
		}
		if(new BigDecimal(ddPrice).compareTo(new BigDecimal(memberPrice))!=-1){
			return CodeContent.getModelByCode(0, "叮当价必须小于会员价", model);
		}
		if(isWarranty){
		    if(!NumberUtils.isDigits(warrantyPeriod)){
				return CodeContent.getModelByCode(0, "保修期格式不正确或为空", model);
		    }
		}
		//防止重复提交
		Object o = memcached.get(loginUser.getId()+"ADDddmGoods");
		if(o!=null){
			return CodeContent.getModelByCode(0, "您操作频繁，请在10秒后重试", model);
		}else {
			memcached.set(loginUser.getId()+"ADDddmGoods",10,"1");
		}
		boolean isRepetitive=true;
		String code=null;
		while (isRepetitive){
			String str=String.valueOf(new Date().getTime());
			code = "DDM"+ str.substring(str.length()-8,str.length());
			DdmGoods ddmGoods=ddmGoodsDao.getByCode(code);
			if(ddmGoods==null){
				isRepetitive=false;
			}
		}
		DdmGoods ddmGoods= new DdmGoods();
		ddmGoods.setName(name.trim());
		ddmGoods.setAbbreviation(abbreviation.trim());
		if(!StringUtils.isEmpty(keyWord))
			ddmGoods.setKeyWord(keyWord);
		ddmGoods.setCode(code.trim());
		ddmGoods.setMainImg(mainImg.trim());
		ddmGoods.setDetailsImg(detailsImg.trim());
		ddmGoods.setGoodsExplain(goodsExplain.trim());
		ddmGoods.setPurchasePrice(new BigDecimal(purchasePrice));
		ddmGoods.setCostPrice(new BigDecimal(costPrice));
		ddmGoods.setDdPrice(new BigDecimal(ddPrice));
		ddmGoods.setMemberPrice(new BigDecimal(memberPrice));
		ddmGoods.setState(false);
		ddmGoods.setCreateUserId(loginUser.getId());
		ddmGoods.setCreateTime(new Date());
		ddmGoods.setIsWarranty(isWarranty);
		ddmGoods.setIsImie(isImie);
		ddmGoods.setSalesVolume(0);
		ddmGoods.setParameter(parameter);
		ddmGoods.setSafeguard(safeguard);
		if(isWarranty){
			ddmGoods.setWarrantyPeriod(Integer.parseInt(warrantyPeriod));
		}
		ddmGoodsDao.add(ddmGoods);

		PriceRecord priceRecord=new PriceRecord();
		priceRecord.setGoodsId(ddmGoods.getId());
		priceRecord.setPrice(ddmGoods.getMemberPrice());
		priceRecord.setUpdateTime(new Date());
		priceRecord.setUpdateUserId(loginUser.getId());
		priceRecordDao.add(priceRecord);
		return CodeContent.getModelByCode(1, "", model);
	}
	/*
	*zlq
	*前台获取商品详情
	 */
	public String portalDetails(ModelMap model,String id,String token){
		DdmGoods ddmGoods=null;
		User loginUser =null;
		if (!StringUtils.isEmpty(token)) {
			loginUser = userDao.getByToken(token);
		}
		if(NumberUtils.isDigits(id)){
			ddmGoods=ddmGoodsDao.getById(Integer.parseInt(id));
		}
		if(ddmGoods!=null){
			if(loginUser!=null){
				List <Collections>  collectionsList=collectionsDao.getByGoodsId(loginUser.getId(),ddmGoods.getId());
				model.put("isCollections",collectionsList.size()>0?true:false);
				model.put("collectionsId",collectionsList.size()>0?String.valueOf(collectionsList.get(0).getId()):"");
				//ffl  添加或修改  我的足迹
				footMarkDao.addFootMark(loginUser,ddmGoods);
			}else {
				model.put("isCollections",false);
				model.put("collectionsId","");
			}
			model.put("id",ddmGoods.getId());
			model.put("name",ddmGoods.getName());
			model.put("keyWord",ddmGoods.getKeyWord()!=null?ddmGoods.getKeyWord():"");
			model.put("abbreviation",ddmGoods.getAbbreviation());
			model.put("state",ddmGoods.getState());
			model.put("code",ddmGoods.getCode());
			model.put("mainImg",ddmGoods.getMainImg());
			model.put("detailsImg",ddmGoods.getDetailsImg());
			model.put("goodsExplain",ddmGoods.getGoodsExplain());
			model.put("memberPrice",ddmGoods.getMemberPrice());
			//商品服务
			List<DdmObligation> ddmObligationList= ddmObligationDao.getByGoodsId(ddmGoods.getId());
			model.put("goodsService",convertDdmObligationList( ddmObligationList));
			//评论
			Comments comments=new Comments();
			comments.setIsValid(true);
			comments.setGoodsId(ddmGoods.getId());
			PageView pageView=commentsDao.queryPageView(-1,2,comments);
			List<Comments> commentsList=pageView.getRecords();
			model.put("commentsList",convertCommentsList(commentsList));
			model.put("commentsCount",pageView.getRowCount());
			Specification specification = new Specification();
			specification.setGoodId(ddmGoods.getId());
			specification.setIsValid(true);
			List <Specification> specificationList=specificationDao.queryPageView(-1,-1,specification).getRecords();
			model.put("isSpecification",specificationList.size()>0?true:false);
			List<ValueAddedServices> valueAddedServicesList=valueAddedServicesDao.getByGoodsId(ddmGoods.getId());
			model.put("isValueAddedServices",valueAddedServicesList.size()>0?true:false);

			Stages stages=new Stages();
			stages.setGoodsId(ddmGoods.getId());
			List<Stages> stagesList=stagesService.getList(-1,-1,stages);
			model.put("stages",stagesList);
			//redis 存入 浏览次数
			JedisPool pool = null;
			Jedis jedis = null;
			try {
				pool = RedisClient.getPool();
				jedis = pool.getResource();
				//浏览次数加一
				jedis.incr("footMark:goodsId:"+id);
			}
			catch (Exception e){
				e.printStackTrace();
			}
			finally {
				pool.returnResource(jedis);
			}
		}
		return 	CodeContent.getModelByCode(1,"success", model);
	}

		public List<ModelMap> convertDdmObligationList(List<DdmObligation> ddmObligationList) {
		List<ModelMap> list = new ArrayList<ModelMap>();
		if (ddmObligationList != null && ddmObligationList.size() > 0) {
			for (DdmObligation ddmObligation : ddmObligationList) {
				ModelMap map = buildModelDdmObligationList(ddmObligation);
				list.add(map);
			}
		}
		return list;
	}
	public ModelMap buildModelDdmObligationList(DdmObligation ddmObligation) {
		ModelMap model = new ModelMap();
		model.put("name",ddmObligation.getName());
		model.put("imgUrl",ddmObligation.getImgUrl());
		model.put("details",ddmObligation.getDetails());
		return  model;
	}
	public List<ModelMap> convertCommentsList(List<Comments> commentsList) {
		List<ModelMap> list = new ArrayList<ModelMap>();
		if (commentsList != null && commentsList.size() > 0) {
			for (Comments comments : commentsList) {
				ModelMap map = buildModelCommentsList(comments);
				list.add(map);
			}
		}
		return list;
	}
	public ModelMap buildModelCommentsList(Comments comments) {
		ModelMap model = new ModelMap();
		User user=userDao.getById(comments.getUserId());
		String userName=user.getRealName();
		if(NumberUtils.isDigits(userName)){
			userName=userName.replaceAll("(\\d{3})\\d{4}(\\d{4})","$1****$2");
		}
		model.put("id",comments.getId());
		model.put("userName",userName);
		model.put("avotorr",user.getAvotorr());
		model.put("gradedValue",comments.getGradedValue());
		model.put("content",comments.getContent()!=null? comments.getContent():"" );
		model.put("imgUrl",comments.getImgUrl()!=null? comments.getImgUrl():"");
		model.put("replyMessage",comments.getReplyMessage()!=null? comments.getReplyMessage():"");
		GoodsOrder goodsOrder=goodsOrderDao.getById(comments.getOrderId());
		if(goodsOrder.getGoodsSpecificationId()!=null){
			GoodSpecification goodSpecification =goodSpecificationDao.getById(goodsOrder.getGoodsSpecificationId());
			model.put("propertiesName",goodSpecification.getPropertiesName());
		}else {
			model.put("propertiesName","");
		}

		return  model;
	}
	/*
	*修改商品
	* zlq
	* token:
	* abbreviation: 商品简称
	* name: 商品名称
	* mainImg: 商品主图
	* detailsImg: 商品详情图
	* goodsExplain: 商品说明
	* purchasePrice: 进货价
	* costPrice: 成本价
	* ddPrice: 叮当价
	* memberPrice: 会员价
	* id: 商品ID
	*  isWarranty：是否保修
    * warrantyPeriod： 保修期(单位：月)
    * isImie：是否有唯一码
    * parameter:详细参数
    * safeguard:售后保障
	 */
	public String  goodsModification(ModelMap model, String token,String abbreviation, String name ,String mainImg,
					   String detailsImg,String goodsExplain,String purchasePrice,String costPrice,
					   String ddPrice,String memberPrice,String id,boolean isWarranty,String warrantyPeriod,
									 boolean isImie,String parameter,String safeguard,String keyWord){

		if (StringUtils.isEmpty(token)) {
			return CodeContent.getModelByCode(-1, "", model);
		}
		User loginUser = userDao.getByToken(token);
		if (loginUser == null) {
			return CodeContent.getModelByCode(-1, "", model);
		}
		if(!NumberUtils.isDigits(id)){
			return CodeContent.getModelByCode(0, "商品ID不能为空", model);
		}
		if (StringUtils.isEmpty(parameter)) {
			return CodeContent.getModelByCode(0, "详细参数不能为空", model);
		}
		parameter=parameter.replace("https://m.9ji.com","");
		if (StringUtils.isEmpty(safeguard)) {
			return CodeContent.getModelByCode(0, "售后保障不能为空", model);
		}
		if (StringUtils.isEmpty(abbreviation)) {
			return CodeContent.getModelByCode(0, "商品简称不能为空", model);
		}
		if (StringUtils.isEmpty(name)) {
			return CodeContent.getModelByCode(0, "商品名称不能为空", model);
		}

		if (StringUtils.isEmpty(mainImg)) {
			return CodeContent.getModelByCode(0, "商品主图不能为空", model);
		}
		if (StringUtils.isEmpty(detailsImg)) {
			return CodeContent.getModelByCode(0, "商品详情图不能为空", model);
		}
		detailsImg=detailsImg.replace("https://m.9ji.com","");
		if (StringUtils.isEmpty(goodsExplain)) {
			return CodeContent.getModelByCode(0, "商品说明不能为空", model);
		}
		if (StringUtils.isEmpty(purchasePrice)) {
			return CodeContent.getModelByCode(0, "进货价不能为空", model);
		}
		if (StringUtils.isEmpty(costPrice)) {
			return CodeContent.getModelByCode(0, "成本价不能为空", model);
		}
		if (StringUtils.isEmpty(memberPrice)) {
			return CodeContent.getModelByCode(0, "会员价不能为空", model);
		}
		if (StringUtils.isEmpty(ddPrice)) {
			return CodeContent.getModelByCode(0, "叮当价不能为空", model);
		}


		if(new BigDecimal(costPrice).compareTo(new BigDecimal(purchasePrice))!=1){
			return CodeContent.getModelByCode(0, "成本价必须大于进货价", model);
		}
		if(new BigDecimal(memberPrice).compareTo(new BigDecimal(costPrice))!=1){
			return CodeContent.getModelByCode(0, "会员价必须大于成本价", model);
		}
		if(new BigDecimal(ddPrice).compareTo(new BigDecimal(memberPrice))!=-1){
			return CodeContent.getModelByCode(0, "叮当价必须小于会员价", model);
		}

		if(isWarranty){
			if(!NumberUtils.isDigits(warrantyPeriod)){
				return CodeContent.getModelByCode(0, "保修期格式不正确或为空", model);
			}
		}
		DdmGoods ddmGoods= ddmGoodsDao.getById(Integer.parseInt(id));
		if(ddmGoods==null){
			return CodeContent.getModelByCode(0, "商品ID不存在", model);
		}

		//防止重复提交
		Object o = memcached.get(loginUser.getId()+"goodsModification");
		if(o!=null){
			return CodeContent.getModelByCode(0, "您操作频繁，请在10秒后重试", model);
		}else {
			memcached.set(loginUser.getId()+"goodsModification",10,"1");
		}
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
		PriceRecord priceRecord=new PriceRecord();
		priceRecord.setGoodsId(ddmGoods.getId());
		//获取最近一次的价格更改记录
		List<PriceRecord> priceRecordList=priceRecordDao.queryPageView(1,1,priceRecord).getRecords();
		if(priceRecordList.size()!=0){
			priceRecord=priceRecordList.get(0);
			//判断最近一次的记录价格是否和更改的价格相同，相同的话不做处理
			if(priceRecord.getPrice().compareTo(new BigDecimal(memberPrice))!=0){
				//判断最近一次的价格记录时间是否和今天相同
				if(formatter.format(priceRecord.getUpdateTime()).equals(formatter.format(new Date()))){
					//相同的日期，对数据进行修改
					priceRecord.setPrice(new BigDecimal(memberPrice));
					priceRecord.setUpdateUserId(loginUser.getId());
					priceRecord.setUpdateTime(new Date());
					priceRecordDao.modify(priceRecord);
				}else {
					//日期不同新添加一条记录
					PriceRecord priceRecord1=new PriceRecord();
					priceRecord1.setGoodsId(ddmGoods.getId());
					priceRecord1.setPrice(new BigDecimal(memberPrice));
					priceRecord1.setUpdateTime(new Date());
					priceRecord1.setUpdateUserId(loginUser.getId());
					priceRecordDao.add(priceRecord1);
				}
			}
		}
		ddmGoods.setName(name.trim());
		ddmGoods.setAbbreviation(abbreviation.trim());
		if(!StringUtils.isEmpty(keyWord))
			ddmGoods.setKeyWord(keyWord);
		ddmGoods.setMainImg(mainImg.trim());
		ddmGoods.setDetailsImg(detailsImg.trim());
		ddmGoods.setGoodsExplain(goodsExplain.trim());
		ddmGoods.setPurchasePrice(new BigDecimal(purchasePrice));
		ddmGoods.setCostPrice(new BigDecimal(costPrice));
		ddmGoods.setDdPrice(new BigDecimal(ddPrice));
		ddmGoods.setMemberPrice(new BigDecimal(memberPrice));
		ddmGoods.setUpdateUserId(loginUser.getId());
		ddmGoods.setUpdateTime(new Date());
		ddmGoods.setIsWarranty(isWarranty);
		ddmGoods.setIsImie(isImie);
		ddmGoods.setParameter(parameter);
		ddmGoods.setSafeguard(safeguard);
		if(isWarranty){
			ddmGoods.setWarrantyPeriod(Integer.parseInt(warrantyPeriod));
		}
		ddmGoodsDao.modify(ddmGoods);
		return CodeContent.getModelByCode(1, "", model);
	}
/*
*zlq
* crm 查询商品列表
* page:页码
* token：
* code：商品编码
* name：商品名称
* abbreviation：商品简称
*state:商品状态
 */
	public String getCrmGoodsList(ModelMap model, String page,String token,String code ,String name,String abbreviation,Boolean state){
		PageView pageview = new PageView();
		int pageNo = 1;
		int pageSize = 20;
		if (NumberUtils.isDigits(page) && !"0".equals(page.trim())) {
			pageNo = NumberUtils.toInt(page);
		}
		if (StringUtils.isEmpty(token)) {
			return CodeContent.getModelByCode(-1, "", model);
		}
		User loginUser = userDao.getByToken(token);
		if (loginUser == null) {
			return CodeContent.getModelByCode(-1, "", model);
		}
		DdmGoods ddmGoods=new DdmGoods();
		if (!StringUtils.isEmpty(code)) {
			ddmGoods.setCode(code.trim());
		}
		if (!StringUtils.isEmpty(name)) {
			ddmGoods.setName(name.trim());
		}
		if (!StringUtils.isEmpty(abbreviation)) {
			ddmGoods.setAbbreviation(abbreviation);
		}
		ddmGoods.setState(state);
		pageview=ddmGoodsDao.queryPageView(pageNo, pageSize,ddmGoods);
		model.put("code",1);
		model.put("msg","success");
		if (pageview != null){
			model.put("datas",convertCrmGoodsList(pageview.getRecords()));
			model.put("recordsTotal", pageview.getRowCount());
			model.put("totalPage", pageview.getPageCount());
			model.put("pageNow", pageview.getPageNow());
		}
		return  new JSONObject(model).toString();
	}
		public List<ModelMap> convertCrmGoodsList(List<DdmGoods> ddmGoodsList) {
		List<ModelMap> list = new ArrayList<ModelMap>();
		if (ddmGoodsList != null && ddmGoodsList.size() > 0) {
			for (DdmGoods ddmGoods : ddmGoodsList) {
				ModelMap map = buildModelCrmGoodsList(ddmGoods);
				list.add(map);
			}
		}
		return list;
	}
	public ModelMap buildModelCrmGoodsList(DdmGoods ddmGoods) {
		ModelMap model = new ModelMap();
		model.put("id",ddmGoods.getId());
		model.put("keyWord",ddmGoods.getKeyWord()!=null?ddmGoods.getKeyWord():"");
		model.put("name",ddmGoods.getName());
		model.put("abbreviation",ddmGoods.getAbbreviation());
		model.put("code",ddmGoods.getCode());
		model.put("state",ddmGoods.getState()?"有效":"无效");
		model.put("purchasePrice",ddmGoods.getPurchasePrice());
		model.put("costPrice",ddmGoods.getCostPrice());
		model.put("ddPrice",ddmGoods.getDdPrice());
		model.put("memberPrice",ddmGoods.getMemberPrice());
		return  model;
	}


	/*
*zlq
* crm 查询所有的商品列表的下拉框
* code：商品编码
* name：商品名称
* abbreviation：商品简称
 */
	public String getCrmAllGoodsListSelect(ModelMap model,String code ,String name,String abbreviation){
		PageView pageview = new PageView();
		DdmGoods ddmGoods=new DdmGoods();
		if (!StringUtils.isEmpty(code)) {
			ddmGoods.setCode(code.trim());
		}
		if (!StringUtils.isEmpty(name)) {
			ddmGoods.setName(name.trim());
		}
		if (!StringUtils.isEmpty(abbreviation)) {
			ddmGoods.setAbbreviation(abbreviation);
		}
		ddmGoods.setState(true);
		pageview=ddmGoodsDao.queryPageView(-1, -1,ddmGoods);
		model.put("code",1);
		model.put("msg","success");
		if (pageview != null){
			model.put("datas",convertCrmAllGoodsListSelect(pageview.getRecords()));
			model.put("recordsTotal", pageview.getRowCount());
			model.put("totalPage", pageview.getPageCount());
			model.put("pageNow", pageview.getPageNow());
		}
		return  new JSONObject(model).toString();
	}

	public List<ModelMap> convertCrmAllGoodsListSelect(List<DdmGoods> ddmGoodsList) {
		List<ModelMap> list = new ArrayList<ModelMap>();
		if (ddmGoodsList != null && ddmGoodsList.size() > 0) {
			for (DdmGoods ddmGoods : ddmGoodsList) {
				ModelMap map = buildModelCrmAllGoodsListSelect(ddmGoods);
				list.add(map);
			}
		}
		return list;
	}
	public ModelMap buildModelCrmAllGoodsListSelect(DdmGoods ddmGoods) {
		ModelMap model = new ModelMap();
		model.put("id",ddmGoods.getId());
		model.put("name",ddmGoods.getName());
		model.put("abbreviation",ddmGoods.getAbbreviation());
		model.put("code",ddmGoods.getCode());
		model.put("state",ddmGoods.getState()?"有效":"无效");
		return  model;
	}

	/*
	*crm获取商品详情
	* zlq
	* token:
	* id:
	 */
	public String getCrmDetails(ModelMap model,String id,String token){
		if (StringUtils.isEmpty(token)) {
			return CodeContent.getModelByCode(-1, "", model);
		}
		User loginUser = userDao.getByToken(token);
		if (loginUser == null) {
			return CodeContent.getModelByCode(-1, "", model);
		}
		if (StringUtils.isEmpty(id)) {
			return CodeContent.getModelByCode(0, "商品ID不能为空", model);
		}
		if (!NumberUtils.isDigits(id)) {
			return CodeContent.getModelByCode(0, "商品ID不为数字", model);
		}
		DdmGoods ddmGoods=ddmGoodsDao.getById(Integer.parseInt(id));
		if(ddmGoods==null){
			return CodeContent.getModelByCode(0, "商品ID不存在", model);
		}
		return CodeContent.getModelByCode(1, "", buildModelCrmDetails(ddmGoods));
	}
	public ModelMap buildModelCrmDetails(DdmGoods ddmGoods) {
		ModelMap model = new ModelMap();
		model.put("id",ddmGoods.getId());
		model.put("name",ddmGoods.getName());
		model.put("abbreviation",ddmGoods.getAbbreviation());
		model.put("code",ddmGoods.getCode());
		model.put("state",ddmGoods.getState()?"有效":"无效");
		model.put("mainImg",ddmGoods.getMainImg());
		model.put("details",ddmGoods.getDetailsImg());
		model.put("goodsExplain",ddmGoods.getGoodsExplain());
		model.put("purchasePrice",ddmGoods.getPurchasePrice());
		model.put("costPrice",ddmGoods.getCostPrice());
		model.put("ddPrice",ddmGoods.getDdPrice());
		model.put("memberPrice",ddmGoods.getMemberPrice());
		model.put("isWarranty",ddmGoods.getIsWarranty()?"保修":"不保修");
		model.put("warrantyPeriod",ddmGoods.getWarrantyPeriod()!=null?ddmGoods.getWarrantyPeriod():"0");
		model.put("isImie",ddmGoods.getIsImie()?"有唯一码":"无唯一码");
		model.put("salesVolume",ddmGoods.getSalesVolume());
		model.put("parameter",ddmGoods.getParameter());
		model.put("safeguard",ddmGoods.getSafeguard());
        model.put("keyWord",ddmGoods.getKeyWord()!=null?ddmGoods.getKeyWord():"" );
		return  model;
	}

	/*
        *zlq
        *前台获取商品详情
         */
	public String portalDetails2(ModelMap model,String id,String goodSpecificationId){
		DdmGoods ddmGoods=null;
		GoodSpecification goodSpecification=null;
		if(NumberUtils.isDigits(id)){
			ddmGoods=ddmGoodsDao.getById(Integer.parseInt(id));
		}
		if(ddmGoods!=null){
			if(NumberUtils.isDigits(goodSpecificationId)){
				goodSpecification=goodSpecificationDao.getById(Integer.parseInt(goodSpecificationId));
			}
//			if(goodSpecification==null){
//				GoodSpecification goodSpecification1 =new GoodSpecification();
//				goodSpecification1.setGoodId(ddmGoods.getId());
//				goodSpecification1.setGoodsState(true);
//				List<GoodSpecification> goodSpecificationList=goodSpecificationDao.queryPageView(-1,-1,goodSpecification1).getRecords();
//				if(goodSpecificationList.size()!=0){
//					goodSpecification=goodSpecificationList.get(0);
//				}
//			}

			model.put("id",ddmGoods.getId());
			model.put("detailsImg",ddmGoods.getDetailsImg());
			model.put("parameter",goodSpecification!=null?goodSpecification.getParameter():ddmGoods.getParameter());
			model.put("safeguard",ddmGoods.getSafeguard());
		}
		return 	CodeContent.getModelByCode(1,"success", model);
	}

/*
*猜你喜欢商品列表
* zlq
 */
	public String guessYouLiveGoods( ModelMap model,String page,String token){
		List<DdmGoods> ddmGoodsList=new ArrayList<DdmGoods>();
		PageView pageview = new PageView();
		int pageNo = 1;
		int pageSize = 12;
		if (NumberUtils.isDigits(page) && !"0".equals(page.trim())) {
			pageNo = NumberUtils.toInt(page);
		}
		User loginUser=null;
		loginUser = userDao.getByToken(token);
		if (loginUser != null) {
			FootMark footMark=new FootMark();
			footMark.setUserId(loginUser.getId());
			footMark.setState(true);
			pageview=footMarkDao.queryPageView(pageNo,pageSize,footMark);
			if(pageview.getRecords().size()!=pageSize){
				ddmGoodsList=ddmGoodsDao.getByPropertyLabel(pageNo,pageSize-pageview.getRecords().size(),"REXIAO").getRecords();
				List<FootMark> footMarkList=pageview.getRecords();
				for(FootMark footMark1:footMarkList){
					DdmGoods ddmGoods=ddmGoodsDao.getById(footMark1.getGoodsId());
					if(ddmGoods.getState()){
						ddmGoodsList.add(ddmGoods);
					}

				}
			}else {
				List<FootMark> footMarkList=pageview.getRecords();
				for(FootMark footMark1:footMarkList){
					DdmGoods ddmGoods=ddmGoodsDao.getById(footMark1.getGoodsId());
					ddmGoodsList.add(ddmGoods);
				}
			}
		}else {
			ddmGoodsList=ddmGoodsDao.getByPropertyLabel(pageNo,pageSize,"REXIAO").getRecords();
		}
		model.put("code",1);
		model.put("msg","success");
		if (ddmGoodsList.size()>0){
			model.put("datas",convertList(ddmGoodsList));
			model.put("recordsTotal", pageview.getRowCount());
			model.put("totalPage", pageview.getPageCount());
			model.put("pageNow", pageview.getPageNow());
		}
		return  new JSONObject(model).toString();
	}

	public List<ModelMap> convertList(List<DdmGoods> ddmGoodsList) {
		List<ModelMap> list = new ArrayList<ModelMap>();
		if (ddmGoodsList != null && ddmGoodsList.size() > 0) {
			for (DdmGoods ddmGoods : ddmGoodsList) {
				ModelMap map = buildModelList(ddmGoods);
				list.add(map);
			}
		}
		return list;
	}
	public ModelMap buildModelList(DdmGoods ddmGoods) {
		ModelMap model = new ModelMap();
		String [] mainImg=ddmGoods.getMainImg().split(",");
		model.put("id",ddmGoods.getId());
		model.put("name",ddmGoods.getName());
		model.put("memberPrice",ddmGoods.getMemberPrice());
		model.put("mainImg",mainImg[0]);
		return  model;
	}

	/*
    *商品上下架
    * zlq
    * token:
    * id: 商品ID
    * state : true:上架 false：下架
     */
	public String updateState(ModelMap model,String token, String id,boolean state ){
		if (StringUtils.isEmpty(token)) {
			return CodeContent.getModelByCode(-1, "", model);
		}
		User loginUser = userDao.getByToken(token);
		if (loginUser == null) {
			return CodeContent.getModelByCode(-1, "", model);
		}
		if (StringUtils.isEmpty(id)) {
			return CodeContent.getModelByCode(0, "商品ID不能为空", model);
		}
		if (!NumberUtils.isDigits(id)) {
			return CodeContent.getModelByCode(0, "商品ID不为数字", model);
		}
		DdmGoods ddmGoods=ddmGoodsDao.getById(Integer.parseInt(id));
		if(ddmGoods==null){
			return CodeContent.getModelByCode(0, "商品ID不存在", model);
		}
		if(state){
			Specification specification=new Specification();
			specification.setGoodId(ddmGoods.getId());
			specification.setIsValid(true);
			List<Specification> specificationList=specificationDao.queryPageView(-1,-1,specification).getRecords();
			if(specificationList.size()!=0){
				GoodSpecification goodSpecification =new GoodSpecification();
				goodSpecification.setGoodId(ddmGoods.getId());
				goodSpecification.setGoodsState(true);
				List <GoodSpecification> goodSpecificationList=goodSpecificationDao.queryPageView(-1,-1,goodSpecification).getRecords();
				if(goodSpecificationList.size()==0){
					return CodeContent.getModelByCode(0, "规格不完整，无法上架", model);
				}
			}
			//上架商品 必须添加过 商品分类  ffl
			List<GoodsRelateCategory> goodsRelateCategoryList=goodsRelateCategoryDao.getByGoodsId(ddmGoods.getId());
			if(goodsRelateCategoryList!=null&goodsRelateCategoryList.size()>=3){
				ddmGoods.setState(state);
				ddmGoodsDao.modify(ddmGoods);
				//商品初始化库存
				goodsInitInventory(ddmGoods,loginUser);
			}else {
				return CodeContent.getModelByCode(0, "商品未 添加商品分类，无法上架", model);
			}
			Random rand = new Random();
			int num=rand.nextInt(100)+1;
			//redis 取 浏览次数
			JedisPool pool = null;
			Jedis jedis = null;
			try {
				pool = RedisClient.getPool();
				jedis = pool.getResource();
				String footMark=jedis.get("footMark:goodsId:"+id);
				if(!NumberUtils.isDigits(footMark)){
					jedis.set("footMark:goodsId:"+id,String.valueOf(num));
				}

			}
			catch (Exception e){
				e.printStackTrace();
			}
			finally {
				pool.returnResource(jedis);
			}

		}else {
			ddmGoods.setState(state);
			ddmGoodsDao.modify(ddmGoods);
		}

		return 	CodeContent.getModelByCode(1,"success", model);
	}

	/*
	*商品初始化库存
	* zlq
	 */
	private  void goodsInitInventory(DdmGoods ddmGoods,User loginUser){
		GoodSpecification goodSpecification =new GoodSpecification();
		goodSpecification.setGoodId(ddmGoods.getId());
		goodSpecification.setGoodsState(true);
		List <GoodSpecification> goodSpecificationList=goodSpecificationDao.queryPageView(-1,-1,goodSpecification).getRecords();
		if(goodSpecificationList.size()!=0){
			for(GoodSpecification goodSpecification1:goodSpecificationList){
				List<DdmShop> ddmShopList=ddmShopDao.queryPageView(-1,-1,new DdmShop()).getRecords();
				for(DdmShop ddmShop1:ddmShopList){
					Inventory inventory=inventoryDao.getOnlyInventory(ddmShop1.getId(),ddmGoods.getId(),goodSpecification1.getId());
					if(inventory==null){
						inventory=new Inventory();
						inventory.setGoodsId(ddmGoods.getId());
						inventory.setShopId(ddmShop1.getId());
						inventory.setSpeciflcationId(goodSpecification1.getId());
						inventory.setTotalInventory(0);
						inventory.setInventory(0);
						inventory.setCreateTime(new Date());
						inventory.setCreateUserId(loginUser.getId());
						inventoryDao.add(inventory);
					}
				}
			}
		}else {
			List<DdmShop> ddmShopList=ddmShopDao.queryPageView(-1,-1,new DdmShop()).getRecords();
			for(DdmShop ddmShop1:ddmShopList){
				Inventory inventory=inventoryDao.getOnlyInventory(ddmShop1.getId(),ddmGoods.getId(),null);
				if(inventory==null){
					inventory=new Inventory();
					inventory.setGoodsId(ddmGoods.getId());
					inventory.setShopId(ddmShop1.getId());
					inventory.setTotalInventory(0);
					inventory.setInventory(0);
					inventory.setCreateTime(new Date());
					inventory.setCreateUserId(loginUser.getId());
					inventoryDao.add(inventory);
				}
			}
		}
	}


	/**
	 * 开放搜索  jsonArray 商品信息修改
	 * ffl
	 * 2017-11-14 11:47:06
	 * @param jsonArray
	 * @return
	 */
	public List<ModelMap> convertJsonArray(JSONArray jsonArray) {
		List<ModelMap> list = new ArrayList<ModelMap>();
		if (jsonArray != null && jsonArray.length() > 0) {
			for (int i=0;i<jsonArray.length();i++) {
				JSONObject json=jsonArray.getJSONObject(i);
				ModelMap map = buildModelJson(json);
				list.add(map);
			}
		}
		return list;
	}
	public ModelMap buildModelJson(JSONObject json) {
		ModelMap model = new ModelMap();
		model.put("goods_id",json.get("goods_id"));
		model.put("name",json.get("name"));
		model.put("member_price",json.get("member_price"));
		model.put("index_name",json.get("index_name"));
		model.put("abbreviation",json.get("abbreviation"));
		String [] mainImg=((String)json.get("main_img")).split(",");
		model.put("main_img",mainImg[0]);
		int commentNum=0;
		int footMarkNum=0;
		String id=(String) json.get("goods_id");
		if(NumberUtils.isDigits(id)) {
			Comments comments = new Comments();
			comments.setGoodsId(NumberUtils.toInt(id));
			comments.setIsValid(true);
			commentNum = commentsDao.getCount(comments);
		}
		//redis 取 浏览次数
		JedisPool pool = null;
		Jedis jedis = null;
		try {
			pool = RedisClient.getPool();
			jedis = pool.getResource();

			String footMark=jedis.get("footMark:goodsId:"+id);
			if(NumberUtils.isDigits(footMark)){
				footMarkNum+=NumberUtils.toInt(footMark);
			}
		}
		catch (Exception e){
			e.printStackTrace();
		}
		finally {
			pool.returnResource(jedis);
		}
		model.put("commentNum",commentNum);
		model.put("footMarkNum",footMarkNum);
		return  model;
	}


    /**
     * 批量处理 redis 商品浏览次数
     */
	public void  footMarkNum(){
		List<DdmGoods> goodsList=ddmGoodsDao.queryAll();

		//redis 取 浏览次数
		JedisPool pool = null;
		Jedis jedis = null;
		try {
			pool = RedisClient.getPool();
			jedis = pool.getResource();
			if(goodsList!=null && goodsList.size()>0){
				for (DdmGoods goods:goodsList){
					makeFootMarkNum(jedis,goods.getId());
				}
			}
		}
		catch (Exception e){
			e.printStackTrace();
		}
		finally {
			pool.returnResource(jedis);
		}
	}

	public  void makeFootMarkNum(Jedis jedis,Integer id){
		Random rand = new Random();
		int num=rand.nextInt(100)+1;
		String footMark=jedis.get("footMark:goodsId:"+id);
		if(!NumberUtils.isDigits(footMark)){
			jedis.set("footMark:goodsId:"+id,String.valueOf(num));
		}
	}

}